package leetcode.Y2024M7;

import org.junit.Test;

import java.util.*;

public class S39 {

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<Integer> state = new ArrayList<>(); // 状态（子集）
        Arrays.sort(candidates); // 对 candidates 进行排序
        int start = 0; // 遍历起始点
        List<List<Integer>> res = new ArrayList<>(); // 结果列表（子集列表）
        backtrack(state, target, candidates, start, res);
        return res;
    }

    void backtrack(List<Integer> state, int target, int[] choices, int start, List<List<Integer>> res) {
        if (target == 0) {
            res.add(new ArrayList<>(state));
            return;
        }
        for (int i = start; i < choices.length; i++) {
            if (target - choices[i] < 0) {
                break;
            }
            state.add(choices[i]);
            backtrack(state, target - choices[i], choices, i, res);
            state.remove(state.size() - 1);
        }
    }

    @Test
    public void test() {
        int[] candidates = {2, 3, 5};
        int target = 8;
        System.out.println(combinationSum(candidates, target));
    }
}
